package com.sl.permission.aspect

import android.content.Context
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.sl.permission.activity.ApplyPermissionActivity
import com.sl.permission.annotation.AopPermission
import com.sl.permission.annotation.PermissionDenied
import com.sl.permission.annotation.PermissionDeniedForever
import com.sl.permission.listener.PermissionRequestCallBack
import com.sl.permission.util.PermissionUtil
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut

/**
 * author： suliang
 * 2022/9/28 10:24
 * describe : 注解织入类
 */
@Aspect
open class PermissionAspect {

    //切入点，匹配改注解标记的任何返回类型、任何参数的任何方法
    //  && @annotation(valuePermission), 方法中添加注解参数，参数名必须一致，用于获取方法参数
    @Pointcut("execution(@com.sl.permission.annotation.AopPermission * * (..))  && @annotation(valuePermission)")
    private fun getPermission(valuePermission:AopPermission){}

    //Advice  参数 valuePermission相当于将上面@PointCut的方法的注解参数传过来
    @Around("getPermission(valuePermission)")
    open fun processPermission(proceedingJoinPoint: ProceedingJoinPoint, valuePermission: AopPermission){
        Log.e("sss ----> "," around调用")
        //1 获取到上下文
        var context : Context? = null
        val aThis = proceedingJoinPoint.`this`      //获取当前正在执行的对象
        if (aThis is FragmentActivity){      //相当于Activity
            context = aThis
        }else if (aThis is Fragment){       //为Fragment
            context = aThis.activity
        }
        //上下文和权限参数为空，则直接返回
        if (context == null ){
            Log.e("AopPermission","上下文为空")
            return
        }
        //2、获取到权限
        val value: Array<String>  = valuePermission.value
        val requestCode : Int = valuePermission.requestCode
        if (value.isEmpty()){
            Log.e("AopPermission","没有查看需要获取的权限")
            return
        }
        //3、跳转到省情权限Activity
        ApplyPermissionActivity.launch(context,value,requestCode,object : PermissionRequestCallBack{
            override fun permissionSuccess() {
                try {
                    proceedingJoinPoint.proceed()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            //取消
            override fun permissionDenied() {
                PermissionUtil.invokeAnnotation(context,PermissionDenied::class.java,requestCode)
            }
            //永久拒绝
            override fun permissionDeniedForever() {
                PermissionUtil.invokeAnnotation(context,PermissionDeniedForever::class.java,requestCode)
            }

        })
    }

}